//! # 认证提供者管理
//!
//! 统一管理多种认证提供者的工厂和管理器

use super::{AuthProvider, AuthProviderType, AuthConfig, JwtAuthProvider, ApiKeyAuthProvider};
use std::collections::HashMap;
use std::sync::Arc;

/// 认证提供者工厂
pub struct AuthProviderFactory;

impl AuthProviderFactory {
    /// 根据配置创建认证提供者
    pub async fn create_provider(
        provider_type: AuthProviderType,
        config: HashMap<String, String>,
    ) -> Result<Box<dyn AuthProvider>, String> {
        match provider_type {
            AuthProviderType::Jwt => {
                // TODO: 从config中解析JWT配置
                let jwt_config = super::jwt::JwtConfig::default();
                let provider = JwtAuthProvider::new(jwt_config).await
                    .map_err(|e| format!("Failed to create JWT provider: {}", e))?;
                Ok(Box::new(provider))
            }
            AuthProviderType::ApiKey => {
                let provider = ApiKeyAuthProvider::new();
                Ok(Box::new(provider))
            }
            _ => Err(format!("Unsupported provider type: {:?}", provider_type)),
        }
    }
}

/// 认证管理器
pub struct AuthManager {
    providers: HashMap<String, Box<dyn AuthProvider>>,
    default_provider: String,
}

impl AuthManager {
    /// 创建新的认证管理器
    pub fn new() -> Self {
        Self {
            providers: HashMap::new(),
            default_provider: "jwt".to_string(),
        }
    }

    /// 添加认证提供者
    pub fn add_provider(&mut self, name: String, provider: Box<dyn AuthProvider>) {
        self.providers.insert(name, provider);
    }

    /// 设置默认提供者
    pub fn set_default_provider(&mut self, name: String) {
        self.default_provider = name;
    }

    /// 获取认证提供者
    pub fn get_provider(&self, name: Option<&str>) -> Option<&dyn AuthProvider> {
        let provider_name = name.unwrap_or(&self.default_provider);
        self.providers.get(provider_name).map(|p| p.as_ref())
    }
}

impl Default for AuthManager {
    fn default() -> Self {
        Self::new()
    }
}